package com.res.share.service.impl;

import com.res.share.common.Constants;
import com.res.share.common.exception.BusinessException;
import com.res.share.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


@Service
public class MailServiceImpl implements MailService {

    private static final Logger logger = LoggerFactory.getLogger(MailService.class);

    @Autowired
    private JavaMailSender mailSender;

    //邮件发件人
    @Value("${mail.fromMail.addr}")
    private String from;

    @Autowired
    TemplateEngine templateEngine;

    @Override
    public void sendMail(String to, String subject, String verifyCode, HttpServletResponse response) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
            messageHelper.setFrom(from);// 发送人的邮箱
            messageHelper.setTo(to);//发给谁  对方邮箱
            messageHelper.setSubject(subject); //标题
            //使用模板thymeleaf
            //Context是导这个包import org.thymeleaf.context.Context;
            Context context = new Context();
            //定义模板数据
            Map<String,Object> map = new HashMap<>();
            map.put("verifyCode",verifyCode);
            context.setVariables(map);
            //获取thymeleaf的html模板
            String emailContent = templateEngine.process("emailTemplate",context); //指定模板路径
            messageHelper.setText(emailContent,true);
            //发送邮件
            mailSender.send(mimeMessage);
            Cookie cookie=new Cookie(Constants.EMIAL_CODE,verifyCode);
            cookie.setPath("/");
            cookie.setMaxAge(120);
            response.addCookie(cookie);
            logger.info("简单邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("模板邮件发送失败->message:{}",e.getMessage());
            throw new BusinessException("邮件发送失败");
        }

    }

}



